package com.zhdl.network.common_client;

import cn.hutool.core.util.HexUtil;
import com.project.command.faq.analysis.ComAnalysis;
import com.project.command.faq.analysis.ComAnalysisData;
import com.project.command.faq.analysis.ComAnalysisResult;
import com.zhdl.network.common_client.dto.ModbusSerialDto;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(CommonSerialClientAnalysis.MODBUS_ANALYSIS)
public class CommonSerialClientAnalysis implements ComAnalysis<ModbusSerialDto, ByteBuf> {

    public static final String MODBUS_ANALYSIS = "mod-bus-rtu";

    /**
     * com原始返回数据,进行解析
     * 将ByteBuf 数据,转换为list初步解析对象
     * 接收示例数据 01 05 00 00 FF 00 8C 3A
     *
     * @param data 需要解析的数据
     * @return 可能多个数据包
     */
    @Override
    public ComAnalysisResult<ModbusSerialDto> analysisData(ComAnalysisData<ByteBuf> data) {
        List<ModbusSerialDto> fullFrames = new ArrayList<ModbusSerialDto>();
        ByteBuf buf = data.getBuf();
        byte[] readData = new byte[buf.readableBytes()];
        buf.readBytes(readData);

        ModbusSerialDto modbusSerialDto = new ModbusSerialDto();
        modbusSerialDto.setFullBuff(readData);
        modbusSerialDto.setUnitBuff(readData);
        fullFrames.add(modbusSerialDto);

        return new ComAnalysisResult<>(fullFrames);
    }


    /**
     * 获取协议头信息
     *
     * @return /
     */
    @Override
    public String getHeadAnalysis() {
        return "";
    }

    /**
     * 协议追加校验位信息（尾部数据）
     *
     * @param cmdStr /
     * @return /
     */
    @Override
    public byte[] getAfterAnalysis(String cmdStr) {
        return HexUtil.decodeHex(cmdStr);
    }
}
